package main

import (
	// "GO-TEST/function"
	"database/sql"
	"fmt"
	"net/http"
	"time"

	// "go-test/function"

	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
)

// type Mssql struct {
// 	*sql.Db
// }

// var (
// 	mssql_data_source 	string = "localhost"
// 	mssql_database 		string = "test"
// 	mssql_user		  	string = "admin"
// 	mssql_passwd		string = "admin"
// 	db					Mssql
// )

func main() {
	fmt.Println("main executed")
	// function.Test()
	// function.Test2()

	r := gin.Default()

	// r.LoadHTMLGlob("templates/**/**")
	r.GET("/ping", func(c *gin.Context) {
		firsname := c.DefaultQuery("firsname", "guest")
		c.String(http.StatusOK, "helo %s ", firsname)
	})

	r.GET("/post", func(c *gin.Context) {
		id, content := sqlqure()

		c.JSON(200, gin.H{
			"status":  "posted",
			"message": "message",
			"data":    content,
			"id":      id,
		})
	})

	r.GET("/index", func(c *gin.Context) {
		firsname := c.DefaultQuery("firsname", "guest")
		message := c.PostForm("message")
		nick := c.DefaultPostForm("nick", "anonymous")
		c.JSON(200, gin.H{
			"status":   "posted",
			"message":  message,
			"nick":     nick,
			"firsname": firsname,
		})
	})

	r.Run(":93")

}

func sqlqure() (id int, content string) {
	// db, err := sql.Open("mysql", "root:xywca4XdifshdPTF@tcp(localhost:3306)/newupdata")

	db, err := sql.Open("mysql", "newupdata:xywca4XdifshdPTF@tcp(localhost:3306)/newupdata?charset=utf8")
	//数据库连接字符串，别告诉我看不懂。端口一定要写/
	if err != nil { //连接成功 err一定是nil否则就是报错
		panic(err.Error())       //抛出异常
		fmt.Println(err.Error()) //仅仅是显示异常
	}

	db.SetConnMaxLifetime(time.Minute * 3) //断开时间设置
	db.SetMaxOpenConns(0)                  //最大打开的连接数,默认值为0表示不限制
	db.SetMaxIdleConns(0)                  //最大闲置的连接数,默认值为0表示不限制

	defer db.Close() //只有在前面用了 panic 这时defer才能起作用，如果链接数据的时候出问题，他会往err写数据
	// rows, err := db.Query("SELECT * FROM `joke` WHERE `id` = 2")
	var status int64
	err = db.QueryRow("SELECT * FROM joke WHERE id = 2").Scan(&id, &content, &status)
	//判断err是否有错误的数据，有err数据就显示panic的数据
	if err != nil {
		panic(err.Error())
		fmt.Println(err.Error())
		return
	}

	// defer rows.Close()
	db.Close() //关闭数据库
	// rows.Next()
	// rows.Scan(&id, &content)
	// fmt.Printf("Id: %d \t Content: %s \n", id, content)
	// fmt.Println(rows.Scan())
	// rows.Scan()
	return
	// return sql.Rows
}
